package com.meisupic.copyright.api.controller;

import static com.meisupic.copyright.common.Constants.AUTH_TYPE_ENTERPRISE;
import static com.meisupic.copyright.common.Constants.AUTH_TYPE_PERSON;
import static com.meisupic.copyright.common.Constants.PUBLISH_STATUS_PUBLISHED;
import static com.meisupic.copyright.common.Constants.RIGHT_OWN_MODE_COOPERATION_WORKS;

import com.meisupic.copyright.domain.vo.CopyrightWorksApiVo;
import com.meisupic.copyright.domain.vo.CopyrightWorksResultApiVo;
import com.meisupic.copyright.domain.vo.RealnameAuthApiVo;
import com.meisupic.copyright.domain.vo.RealnameCallBackParamsVo;
import com.meisupic.copyright.domain.vo.RegisterCallBackParamsVo;
import com.meisupic.copyright.exception.BizException;
import com.meisupic.copyright.service.ApiService;
import com.meisupic.copyright.support.Message;
import com.meisupic.copyright.util.ValidatorUtil;
import com.meisupic.copyright.validategroups.AuthTypeGroup;
import com.meisupic.copyright.validategroups.EnterpriseAuthGroup;
import com.meisupic.copyright.validategroups.PersonAuthGroup;
import com.meisupic.copyright.validategroups.Published;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Api(value = "版权登记接口")
public class ApiController {

  @Autowired
  Validator hibernateValidator;

  @Autowired
  ApiService apiService;


  @PostMapping("/realNameAuth/save")
  @ApiOperation(value = "实名认证接口")
  public Message<RealnameAuthApiVo> SaveRealNameAuth(
      @RequestBody @Validated(value = AuthTypeGroup.class)
          RealnameAuthApiVo realnameAuthApiVo) {
    Set<ConstraintViolation<RealnameAuthApiVo>> resultSet = null;
    if (AUTH_TYPE_PERSON.equals(realnameAuthApiVo.getAuthType())) {
      Integer[] types = {1, 2, 3, 4, 9};
      if (!Arrays.asList(types).contains(realnameAuthApiVo.getDocumentType())) {
        return Message.error("证件类型错误");
      }
      switch (realnameAuthApiVo.getDocumentType()) {
        case 1:
          if (!ValidatorUtil.isIDCardNo(realnameAuthApiVo.getDocumetNo())) {
            return Message.error("身份证号码不合法");
          }
          break;
        default:
          break;
      }
      resultSet = hibernateValidator
          .validate(realnameAuthApiVo, PersonAuthGroup.class);
    } else if (AUTH_TYPE_ENTERPRISE.equals(realnameAuthApiVo.getAuthType())) {
      Integer[] types = {5, 6, 7, 8, 9};
      if (!Arrays.asList(types).contains(realnameAuthApiVo.getDocumentType())) {
        return Message.error("证件类型错误");
      }
      switch (realnameAuthApiVo.getDocumentType()) {
        case 6:
          if (!ValidatorUtil.isOrgCode(realnameAuthApiVo.getDocumetNo())) {
            return Message.error("组织机构代码错误");
          }
          break;
        case 5:
          if (!ValidatorUtil.isUnicode(realnameAuthApiVo.getDocumetNo())) {
            return Message.error("社会统一信用代码错误");
          }
          break;
        default:
          break;
      }
      resultSet = hibernateValidator
          .validate(realnameAuthApiVo, EnterpriseAuthGroup.class);
    }
    if (!resultSet.isEmpty()) {
      for (ConstraintViolation<RealnameAuthApiVo> constraintViolation : resultSet) {
        throw new BizException(constraintViolation.getMessage());
      }
    }
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    realnameAuthApiVo.setClientId(principal.toString());
    apiService.saveRealNameAuth(realnameAuthApiVo);
    return Message.success(realnameAuthApiVo);
  }


  @PostMapping("/copyright/save")
  @ApiOperation(value = "作品登记接口")
  public Message<CopyrightWorksApiVo> saveCopyright(
      @RequestBody @Validated CopyrightWorksApiVo copyrightWorksApiVo) {

    if (PUBLISH_STATUS_PUBLISHED == copyrightWorksApiVo.getPublishStatus()) {
      Set<ConstraintViolation<CopyrightWorksApiVo>> resultSet = hibernateValidator
          .validate(copyrightWorksApiVo, Published.class);
      if (!resultSet.isEmpty()) {
        for (ConstraintViolation<CopyrightWorksApiVo> constraintViolation : resultSet) {
          throw new BizException(constraintViolation.getMessage());
        }
      }
      Date firstPublishDate = copyrightWorksApiVo.getFirstPublishDate();
      Date creativeDate = copyrightWorksApiVo.getCreationDate();
      if (firstPublishDate.before(creativeDate)) {
        throw new BizException("首次发表日期不能小于创作日期");
      }
    }
    if (copyrightWorksApiVo.getRightOwnMode() == RIGHT_OWN_MODE_COOPERATION_WORKS) {
      throw new BizException("权利归属方式值错误");
    }
    apiService.saveCopyrightWorks(copyrightWorksApiVo);
    return Message.success(copyrightWorksApiVo);
  }


  @ApiOperation(value = "版权登记查询接口")
  @ApiImplicitParam(name = "id", value = "登记作品id", required = true, paramType = "path")
  @GetMapping("/copyright/query/{id}")
  public Message<CopyrightWorksResultApiVo> queryRealNameAuth(@PathVariable Long id) {
    CopyrightWorksResultApiVo resultApiVo = apiService.queryCopyrightWorksById(id);
    return Message.success(resultApiVo);
  }

  @ApiOperation(value = "版权登记查询接口",hidden = true)
  @PostMapping(value = "/callBack")
  public Message callBack(@RequestBody RealnameCallBackParamsVo realnameCallBackParamsVo,
      @RequestBody RegisterCallBackParamsVo registerCallBackParamsVo) {
    return Message.success(null);
  }
}
